/*
 * Copyright (c) 2008 SQLI http://www.sqli.com/
 * Author: Olivier CARPENTIER
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy 
 * of this software and associated documentation files (the "Software"), to deal in 
 * the Software without restriction, including without limitation the rights to use, 
 * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the 
 * Software, and to permit persons to whom the Software is furnished to do so, subject 
 * to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all 
 * copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;

namespace SQLI.WSS.WebControls.DataSource
{
    /// <summary>
    /// Configuration form for the DataSource.
    /// </summary>
    public partial class ConfigWSSListDataSource : Form
    {
        private IServiceProvider _serviceProvider;
        private WSSListDataSource _component;
        private WSSListDataSourceDesigner _designer;

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigWSSListDataSource"/> class.
        /// </summary>
        public ConfigWSSListDataSource()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ConfigWSSListDataSource"/> class.
        /// </summary>
        /// <param name="provider">The provider.</param>
        /// <param name="designer">The designer.</param>
        public ConfigWSSListDataSource(IServiceProvider provider, WSSListDataSourceDesigner designer)
        {
            InitializeComponent();

            _serviceProvider = provider;
            _component = designer.Component as WSSListDataSource;
            _designer = designer;

            //Initialize data from component
            this.SharePointSiteUrl.Text = _component.WebSiteUrl;
            this.SharePointListName.Text = _component.ListName;
            this.SharePointViewName.Text = _component.ViewName;
            if (_component.InitialisationMode == InitialisationMode.UseCurrentContext)
                radioButtonCurrentContexte.Checked = true;
            else
                radioButtonExplicitUrl.Checked = true;
            this.checkBoxDelete.Checked = _component.AllowDelete;
            this.checkBoxInsert.Checked = _component.AllowInsert;
            this.checkBoxUpdate.Checked = _component.AllowUpdate;
        }

        /// <summary>
        /// Handles the Load event of the ConfigWSSListDataSource control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void ConfigWSSListDataSource_Load(object sender, EventArgs e)
        {
        }

        /// <summary>
        /// Handles the Click event of the buttonOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (this.radioButtonCurrentContexte.Checked)
            {
                TypeDescriptor.GetProperties(_component)["InitialisationMode"].SetValue(_component, InitialisationMode.UseCurrentContext);
			}
            else
            {
                TypeDescriptor.GetProperties(_component)["InitialisationMode"].SetValue(_component, InitialisationMode.UseExplicitServerUrl);
                TypeDescriptor.GetProperties(_component)["WebSiteUrl"].SetValue(_component, this.SharePointSiteUrl.Text);
            }

            TypeDescriptor.GetProperties(_component)["ListName"].SetValue(_component, this.SharePointListName.Text);
            TypeDescriptor.GetProperties(_component)["ViewName"].SetValue(_component, this.SharePointViewName.Text);
            TypeDescriptor.GetProperties(_component)["AllowDelete"].SetValue(_component, this.checkBoxDelete.Checked);
            TypeDescriptor.GetProperties(_component)["AllowUpdate"].SetValue(_component, this.checkBoxUpdate.Checked);
            TypeDescriptor.GetProperties(_component)["AllowInsert"].SetValue(_component, this.checkBoxInsert.Checked);
            
            //Set the fields
            FieldsCollection fields = new FieldsCollection();
            CheckedListBox.CheckedItemCollection cols = this.SharepointQueryFields.CheckedItems;
            foreach (object obj in cols)
            {
                string field = (string)obj;
                fields.Add(new Field(field));
            }
            TypeDescriptor.GetProperties(_component)["Fields"].SetValue(_component, fields);
            
            _designer.RefreshSchemaInternal(true);

            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        /// <summary>
        /// Handles the CheckedChanged event of the radioButtonCurrentContexte control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void radioButtonCurrentContexte_CheckedChanged(object sender, EventArgs e)
        {
            if (this.radioButtonCurrentContexte.Checked)
                this.panelUrl.Enabled = false;
            else
                this.panelUrl.Enabled = true;
        }

        /// <summary>
        /// Handles the TextChanged event of the SharePointListName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SharePointListName_TextChanged(object sender, EventArgs e)
        {
            try
            {
                using (SPWeb web = new SPSite(this.SharePointSiteUrl.Text).OpenWeb())
                {
                    this.SharePointViewName.Items.Clear();

                    SPList list = web.Lists[this.SharePointListName.Text];
                    foreach (SPView view in list.Views)
                        this.SharePointViewName.Items.Add(view.Title);
                    
                    this.SharepointQueryFields.Items.Clear();
                    StringCollection selectedFields = new StringCollection();
                    foreach (string field in list.DefaultView.ViewFields)
                        selectedFields.Add(field);
                        
                    foreach (SPField field in list.Fields)
                    {
                        bool selected = selectedFields.Contains(field.InternalName);
                        this.SharepointQueryFields.Items.Add(field.InternalName, selected);
                    }

                    this.SharePointViewName.Text = list.DefaultView.Title;

                    web.Close();
                }
            }
            catch (Exception )
            {
                //MessageBox.Show(exc.Message);
            }
        }

        /// <summary>
        /// Handles the TextChanged event of the SharePointViewName control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void SharePointViewName_TextChanged(object sender, EventArgs e)
        {
            try
            {
                using (SPWeb web = new SPSite(this.SharePointSiteUrl.Text).OpenWeb())
                {
                    SPList list = web.Lists[this.SharePointListName.Text];
                    SPView view = list.Views[this.SharePointViewName.Text];

                    StringCollection selectedFields = new StringCollection();
                    foreach (string field in view.ViewFields)
                        selectedFields.Add(field);

                    this.SharepointQueryFields.Items.Clear();
                    
                    foreach (SPField field in list.Fields)
                    {
                        bool selected = selectedFields.Contains(field.InternalName);
                        this.SharepointQueryFields.Items.Add(field.InternalName, selected);
                    }

                    web.Close();
                }
            }
            catch (Exception )
            {
                //MessageBox.Show(exc.Message);
            }
        }

        /// <summary>
        /// Handles the Click event of the buttonWhere control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonWhere_Click(object sender, EventArgs e)
        {
            List<string> whereFields = new List<string>();
            foreach (object item in this.SharepointQueryFields.Items)
                whereFields.Add((string)item);
            
            using (ConfigWSSListDataSourceWhere whereDialog = new ConfigWSSListDataSourceWhere())
            {
                whereDialog.ComponentDataSource = this._component;
                whereDialog.SetFields(whereFields);
                whereDialog.ShowDialog(this);
            }
        }

        /// <summary>
        /// Handles the Click event of the buttonOrderBy control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonOrderBy_Click(object sender, EventArgs e)
        {
            List<string> whereFields = new List<string>();
            foreach (object item in this.SharepointQueryFields.Items)
                whereFields.Add((string)item);
            
            using (ConfigWSSListDataSourceOrderBy orderByDialog = new ConfigWSSListDataSourceOrderBy())
            {
                orderByDialog.ComponentDataSource = this._component;
                orderByDialog.SetFields(whereFields);
                orderByDialog.ShowDialog(this);
            }
        }

        /// <summary>
        /// Handles the Click event of the buttonGo control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void buttonGo_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            try
            {
                using (SPWeb web = new SPSite(this.SharePointSiteUrl.Text).OpenWeb())
                {
                    this.SharePointListName.Items.Clear();

                    SPListCollection lists = web.Lists;
                    foreach (SPList list in lists)
                    {
                        this.SharePointListName.Items.Add(list.Title);
                    }
                    this.SharePointListName.SelectedIndex = 0;
                    web.Close();

                    this.label1ConnectionResult.Text = "Connection with sharepoint site successful.";
                    this.label1ConnectionResult.ForeColor = Color.Green;
                }
            }
            catch (Exception)
            {
                this.label1ConnectionResult.Text = "Automatic connection with sharepoint site failed.";
                this.label1ConnectionResult.ForeColor = Color.Red;
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

    }
}